import type { BaseModel } from "@/type/ResponseData";
import type { kvModel } from "@/type/ResponseData";
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'

export const is = (val: unknown, type: string) => {
  return toString.call(val) === `[object ${type}]`
}
export const isObject = (val: any): val is Record<any, any> => {
  return val !== null && is(val, 'Object')
}
export function DeconstructionKvModel<T extends BaseModel>(v: T) {
  const keys = Object.keys(v)
  keys.forEach(r => {
    const _r = r as keyof typeof v;
    if (isObject(v[_r])) {
      const kv = v[_r] as unknown as kvModel
      if (kv != null) {
        (v[_r] as unknown as string) = kv._k
      }
    }
  })
}
export function extractKvValue(d?: kvModel | string, def?: string) {
  if (!d) return def
  if (is(d, 'string'))
    return d as string
  return (d as kvModel)._v as string
}
export function extractKvKey(d?: kvModel | string) {
  if (!d) return undefined
  if (is(d, 'string'))
    return d
  return (d as kvModel)._k
}
export function safeAssign<T extends object, K extends string, V>(
  obj: T,
  key: K,
  value: V
): T & Record<K, V> {
  (obj as any)[key] = value
  return obj as T & Record<K, V>
}

export const exportToExcle = async (excelData: string[][]) => {
  try {
    const ws = XLSX.utils.aoa_to_sheet(excelData)
    const wb = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(wb, ws, '课程安排')
    const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
    const blob = new Blob([excelBuffer], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    })
    setTimeout(() => {
      saveAs(blob, `员工数据_${new Date().toISOString().split('T')[0]}.xlsx`)
    }, 1000)
  } catch (error) {
    console.error('导出Excel失败:', error)
  }
}